package com.se.utils;


import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Text;

import java.nio.file.Path;
import java.util.Objects;

import static com.se.mainView.MainViewController.MAX_IMAGE_SIZE;

public class SpecialStyleTextFactory {
    private static final String originStyle = "-fx-fill: #0078d4;";

    private SpecialStyleTextFactory() {
    }

    public static Text createFileMessageText(ClientMessage fileMessage) {
        Path path = Path.of(fileMessage.getContent());
        String fileName = path.getFileName().toString();
        Text text = new Text();
        text.setStyle(originStyle);
        text.setText(fileName);
        return text;
    }

    public static ImageView createImageMessage(ClientMessage imageMessage) {
        Path path = Path.of(imageMessage.getContent());
        String fileName = path.getFileName().toString();

        //如果图片/文件消息不是自己发的，那么就需要改变路径
        if(!imageMessage.getSendUser().equals(ServiceUtils.getSpeaker().getUserName())) {
            Path newPath = Path.of(ServiceUtils.FILE_STORAGE_PATH);
            path = newPath.resolve(fileName);
        }
        Image image = new Image("file:/" + path);
        ImageView imageView = new ImageView();
        if(image.isError()) {
            String errorPath = Objects.requireNonNull(SpecialStyleTextFactory
                    .class.getResource("/image/ImageLoading.jpg")).toString();
            image = new Image(errorPath);
            imageView.setImage(image);
            imageView.setFitWidth(40);
            imageView.setFitHeight(40);
        }
        else {
            imageView.setImage(image);
            imageView.setPreserveRatio(true);

            if(image.getHeight() > MAX_IMAGE_SIZE || image.getWidth() > MAX_IMAGE_SIZE) {
                if (image.getWidth() >= image.getHeight()) {
                    imageView.setFitWidth(MAX_IMAGE_SIZE); // 宽图按宽度缩放
                } else {
                    imageView.setFitHeight(MAX_IMAGE_SIZE); // 高图按高度缩放
                }
            }
            else {
                imageView.setFitHeight(image.getHeight());
                imageView.setFitWidth(image.getWidth());
            }
        }

        return imageView;
    }
}
